import { login, getInfo } from '@/api/user'
import { updateMyInfo } from '@/api/admin'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userId: '',
  companyId: '',
  departmentId: '',
  name: '',
  realname: '',
  level: '',
  avatar: '/favicon.ico',
  roles: [],
  grant_type: 'password',
  client_id: 'jxlhApp',
  client_secret: 'jxlhApp',
  scope: 'all'
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_COMPANY_ID: (state, companyId) => {
    state.companyId = companyId
  },
  SET_DEPARTMENT_ID: (state, departmentId) => {
    state.departmentId = departmentId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_REALNAME: (state, realname) => {
    state.realname = realname
  },
  SET_LEVEL: (state, level) => {
    state.level = level
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit, state }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        grant_type: state.grant_type,
        client_id: state.client_id,
        client_secret: state.client_secret,
        scope: state.scope
      }).then(data => {
        commit('SET_TOKEN', data.access_token)
        setToken(data.access_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        if (!data) {
          reject('认证失败，请您重新登陆')
        }
        const { authorities, username, id, companyId, departmentId, realname, level } = data
        const roleArr = []
        if (authorities && authorities.length > 0) {
          for (let index = 0; index < authorities.length; index++) {
            roleArr.push(authorities[index].authority)
          }
        }
        if (roleArr && roleArr.length <= 0) {
          reject('您的帐号未分配权限，请联系管理！')
        }
        data.roles = roleArr
        commit('SET_ROLES', roleArr)
        commit('SET_NAME', username)
        commit('SET_USER_ID', id)
        commit('SET_COMPANY_ID', companyId)
        commit('SET_DEPARTMENT_ID', departmentId)
        commit('SET_REALNAME', realname)
        commit('SET_LEVEL', level)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USER_ID', '')
      commit('SET_COMPANY_ID', '')
      commit('SET_DEPARTMENT_ID', '')
      commit('SET_REALNAME', '')
      commit('SET_LEVEL', '')
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USER_ID', '')
      commit('SET_COMPANY_ID', '')
      commit('SET_DEPARTMENT_ID', '')
      commit('SET_REALNAME', '')
      commit('SET_LEVEL', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'
    commit('SET_TOKEN', token)
    setToken(token)
    const { roles } = await dispatch('getInfo')
    resetRouter()
    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)
    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  async changeRealname({ commit }, data) {
    return new Promise((resolve, reject) => {
      updateMyInfo(data).then(() => {
        commit('SET_REALNAME', data.realname)
        commit('SET_NAME', data.phone)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
